import axios from "axios";
import {storageHook} from "@/hooks/storagehook.ts";
import {StorageStrategy} from "@/util/storage.ts";
import {REFRESH_TOKEN_KEY, TOKEN_KEY, TOKEN_PREFIX} from "@/common/comConstant/commoncanstant.ts";
import {Result} from "@/common/comTypes/commonTypes.ts";
import {sendGlobalMessage} from "@/hooks/globalmessage.ts";
import {GlobalMessage, MessageType} from "@/event/eventglobalmessage.ts";
import {refreshTokenApi, setTokenToCookies} from "@/common/commonJs/login.ts";
import {AuthFailError, BusinessError} from "@/common/comTypes/errorType.ts";
import router from "@/router/router.ts";

const VITE_UI_MODE = JSON.parse(import.meta.env.VITE_UI_MODE) || false
const HTTP_SUCCESS_STATUS = 200
export const HTTP_SUCCESS_CODE = 1
export const HTTP_FAIL_CODE = -1
const HTTP_NO_AUTH_CODES = [401, 402, 403]

function getToken(): string {
    return storageHook(StorageStrategy.COOKIE_STORAGE).storage.get(TOKEN_KEY)
}

function getRefreshToken(): string {
    return storageHook(StorageStrategy.COOKIE_STORAGE).storage.get(REFRESH_TOKEN_KEY)
}

const service = axios.create(
    {
        withCredentials: true,
        //获取环境变量中的请求地址 和 前缀
        baseURL: import.meta.env.VITE_APP_BASE_SERVICE_API + import.meta.env.VITE_APP_BASE_API,
        //过期时间
        timeout: import.meta.env.VITE_APP_EXPIRED_TIME
    })
//请求拦截器
service.interceptors.request.use(config => {
    config.headers["X-Requested-With"] = "XMLHttpRequest";
    config.headers["Request-Start"] = new Date().getTime();
    const token = getToken()
    const refreshToken = getRefreshToken()
    if (token) {
        config.headers.set(TOKEN_KEY, TOKEN_PREFIX + token);
    }
    if (refreshToken) {
        config.headers.set(REFRESH_TOKEN_KEY, TOKEN_PREFIX + refreshToken)
    }
    return config;
}, error => {
    return
})


//响应拦截器
service.interceptors.response.use(
    (response) => {
        console.log("响应成功:")
        console.log(response)
        let status = response.status
        if (status == HTTP_SUCCESS_STATUS) {
            let code = response.data.code
            if (code == HTTP_SUCCESS_CODE || code == undefined) {
                //成功的状态 直接返回
                return response.data
            } else if (code == HTTP_FAIL_CODE) {
                throw new BusinessError(response.data?.message || "服务异常")
            }
        }
    },
    //请求失败
    async (error) => {
        console.log(error)
        const code = error.response.data?.code
        const status = error.response.status
        const message = error.response.data?.message || "服务异常"
        if (VITE_UI_MODE) {
            return Result.successWithCodeAndMsg({}, 1, "UI模式")
        } else if (HTTP_NO_AUTH_CODES.includes(status) || HTTP_NO_AUTH_CODES.includes(code)) {
            //当前请求失败接口信息
            const {method, url, params, data, headers} = error.config || {};
            const contentType = headers?.['Content-Type'] || headers?.['content-type']
            console.log('失败的请求方法:', method);
            console.log('失败的接口路径:', url);
            console.log("失败接口路径参数:", params)
            console.log("失败接口请求体参数", data)
            console.log("刷新token中...")
            console.log("content-type:", contentType)
            const refreshToken = getRefreshToken()
            if (refreshToken && url != '/noAuth/refreshToken') {
                //刷新token
                let res = await refreshTokenApi()
                if (res.isSuccess()) {
                    setTokenToCookies(res.data?.token, res.data?.expirationTime, res.data?.refreshToken, res.data?.refreshTime)
                    //重新请求中断接口
                    return axiosHttp.request(method, url, params, data, contentType)
                } else {
                    //认证异常
                    throw new AuthFailError("长时间未操作,请重新登录")
                }
            } else {
                //认证异常
                throw new AuthFailError("长时间未操作,请重新登录")
            }
        } else if (code == HTTP_FAIL_CODE) {
            //通用业务异常
            throw new BusinessError(message)
        }
    }
);

//请求方法
export const axiosHttp = {
    get: async (url: string, params ?: {}): Promise<Result<any>> => {
        try {
            let res = await service.get(url, {params: params})
            return Promise.resolve(Result.success(res?.data));
        } catch (error) {
            if (error instanceof Error) {
                return handlerError(error)
            }
            return Promise.resolve(Result.fail("未知错误"))

        }

    },

    post: async (url: string, params?: {}, config?: {}): Promise<Result<any>> => {
        try {
            let res = await service.post(url, params, config);
            console.log(res)
            return Promise.resolve(Result.success(res?.data));
        } catch (error) {
            if (error instanceof Error) {
                return handlerError(error)
            }
            return Promise.resolve(Result.fail("未知错误"))

        }
    },

    put: async (url: string, params?: {}, config?: {}): Promise<Result<any>> => {

        try {
            let res = await service.put(url, params, config)
            return Promise.resolve(Result.success(res?.data));
        } catch (error) {
            if (error instanceof Error) {
                return handlerError(error)
            }
            return Promise.resolve(Result.fail("未知错误"))

        }

    },

    delete: async (url: string, params?: {}): Promise<Result<any>> => {

        try {
            let res = await service.delete(url, {params: params})
            return Promise.resolve(Result.success(res?.data));
        } catch (error) {
            if (error instanceof Error) {
                return handlerError(error)
            }
            return Promise.resolve(Result.fail("未知错误"))

        }
    },
    //发送请求
    request(method: string, url: string, params: any, data: any, contentType: string) {
        if (method == 'get' || method == 'delete') {
            return axiosHttp[method](url, params)
        } else if (method == 'post' || method == 'put') {

            return axiosHttp[method](url, data, {
                headers: {
                    "content-type": contentType
                }
            })
        }
    }
}

//处理异常
function handlerError(error: Error): Promise<Result<any>> {
    if (error instanceof AuthFailError || error instanceof BusinessError) {
        sendGlobalMessage(new GlobalMessage().buildType(MessageType.ERROR).buildMessage(error.message))
        if (error instanceof AuthFailError) {
            //跳转至登录页
            setTimeout(() => {
                router.push("/login").then(res => {
                    console.log("跳转至登录页")
                })
            }, 1500)
        }
        return Promise.resolve(Result.fail(error.message))

    }
    return Promise.resolve(Result.fail("xx"))
}

